import static java.lang.System.out;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;

public class ClientLogin extends JFrame implements ActionListener {
	BufferedImage appIcon;
	BufferedImage backgroundImage;
	JPanel usernamePanel;
	JPanel passwordPanel;
	JPanel checkboxPanel;
	JPanel statusPanel;
	JLabel userText;
	JTextField usernameField;
	JLabel passwordText;
	JPasswordField passwordField;
	JButton submit;
	String appName = "Mobile Control";
	String userName="";
	String password="";
	JLabel warningMsg;
	
	String userInfoFileName = "userInfo.bin";
	
	Checkbox rememberUserCheckbox;
	PcClient myPC;
	
	public ClientLogin(){
		try {
            appIcon = ImageIO.read(
                this.getClass().getResource("app_icon.jpg"));
            backgroundImage = ImageIO.read(
                    this.getClass().getResource("bg.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
		drawUI();
		
	}
	
	@SuppressWarnings("deprecation")
	public void drawUI(){	
		
		this.setIconImage(appIcon);
		this.setTitle(appName);
		this.setUndecorated(false);
		this.setSize(250, 175);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		//this.setBackground(Color.black);
		createPanel();
		this.add(usernamePanel,BorderLayout.NORTH);
		this.add(passwordPanel,BorderLayout.CENTER);
		passwordPanel.add(checkboxPanel);
		this.add(statusPanel,BorderLayout.SOUTH);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	public void createPanel(){
		usernamePanel = new JPanel();
		passwordPanel = new JPanel();
		statusPanel = new JPanel();
		checkboxPanel = new JPanel();
		userText = new JLabel("Username:");
		passwordText = new JLabel("Password:");
		usernameField = new JTextField(10);
		passwordField = new JPasswordField(10);
		submit = new JButton("Submit");
		submit.addActionListener(this);
		warningMsg = null;
		
		usernameField.setPreferredSize(new Dimension(120,25));
		passwordField.setPreferredSize(new Dimension(120,25));
		
		rememberUserCheckbox = new Checkbox("Remember user");
		checkIfRemember();
		usernamePanel.add(userText);
		usernamePanel.add(usernameField);
		passwordPanel.add(passwordText);
		passwordPanel.add(passwordField);
		checkboxPanel.add(rememberUserCheckbox);
		statusPanel.add(submit);
		
		
	}
	
	private void checkIfRemember(){
		File userInfoFile = new File(userInfoFileName);
		if(userInfoFile.exists()){
			rememberUserCheckbox.setState(true);
			 byte[] buffer = new byte[(int)userInfoFile.length()];
		        try {
		        	 FileInputStream fin = new FileInputStream(userInfoFile);
		            fin.read(buffer);
		            fin.close();
		        }catch(Exception e){
		        	System.err.println(e);
		        }
		        String s = new String(buffer);
		        String[] userInfo = s.split(" ");
		        usernameField.setText(userInfo[0]);
		        passwordField.setText(userInfo[1]);
		        
		}
		else{
			rememberUserCheckbox.setState(false);
		}	
	}
	
	 private static void processBuffer(byte[] buffer, int start, int end) {
	        System.out.write(buffer, start, end);
	    }
	
	private void createSystemTray()
	{
		 if (!SystemTray.isSupported()) {
	            System.out.println("SystemTray is not supported");
	            return;
	     }
		 Toolkit toolkit = Toolkit.getDefaultToolkit();
		 Image image = toolkit.getImage("app_icon.jpg");
	        PopupMenu pop = new PopupMenu();
	        final TrayIcon trayIcon = new TrayIcon(appIcon,appName);
	        trayIcon.setImageAutoSize(true);
	        final SystemTray tray = SystemTray.getSystemTray();
	        
	        MenuItem exitItem = new MenuItem("Exit");
	        exitItem.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent e) {
	              myPC.terminate();
	              tray.remove(trayIcon);
	              System.exit(0);
	            }
	          }
	        );
	        MenuItem settingItem = new MenuItem("Settings");
	        settingItem.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					int curSen = myPC.getScale();
					new Setting(curSen,myPC);
				}
	        }
	        );
	        settingItem.addActionListener(this);
	        pop.add(settingItem);
	        pop.add(exitItem);
	       
	        trayIcon.setPopupMenu(pop);
	       
	        try {
	            tray.add(trayIcon);
	        } catch (AWTException e) {
	            System.out.println("TrayIcon could not be added.");
	        }
	        trayIcon.displayMessage("Greetings:", appName + " is on",  TrayIcon.MessageType.INFO);
	}
	
	public String getUsername(){
		return userName;
	}
	
	public String getPassword(){
		return password;
	}

	private void saveUserInfo(String name,String pass){
		try{
			DataOutputStream os = new DataOutputStream(new FileOutputStream(userInfoFileName));
			String info = name + " " + pass;
			byte[] buffer = info.getBytes();
			os.write(buffer);
			 os.close();
		}catch(Exception e){
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==submit){
			userName = usernameField.getText();
			password = passwordField.getText();
			// If user check the remember user checkbox, save the user info
			if(rememberUserCheckbox.getState())
			{
				saveUserInfo(userName,password);
				System.err.println("Not delete");
			}
			else{
				File userInfoFile = new File(userInfoFileName);
				if(userInfoFile.exists()){
					
					if(userInfoFile.delete()){

						System.err.println("delete succeed");
					}
					else{
						System.err.println("delete failed");
					}
					
				}
			}
			
			if( userName != "" && password != "" )
			{
				this.setVisible(false);
				String servername = "lore.cs.purdue.edu";
				try {
					myPC = new PcClient( userName + "&" + password , servername );
					createSystemTray();
				} catch(Exception ex) {
	        		out.println( "Error --> " + ex.getMessage());
				}
			}
			//else if(e.getSource()==)
			else
			{
				if( warningMsg == null )
				{
					warningMsg = new JLabel("ERROR: Username or password can not be empty");
					statusPanel.add( warningMsg );
				}
				
				this.setVisible(false);
				this.dispose();
			}
		}
	}
	
	public static void main(String[] args){
		new ClientLogin();
	}
}
